package com.cloudbroker.bcs.platform.dav.middle.service.impl;

import static com.cloudbroker.bcs.platform.dav.bizapi.constants.WechatUrl.SEND_MESSAGE;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.annotation.Resource;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.MassMessageForm;
import com.cloudbroker.bcs.platform.dav.middle.dao.MassMessageDao;
import com.cloudbroker.bcs.platform.dav.middle.entity.MassMessage;
import com.cloudbroker.bcs.platform.dav.middle.service.MassMessageService;
import com.cloudbroker.bcs.platform.dav.middle.service.base.TenantServiceImplBase;

/**
 * Created by wangxu13798 on 2016/7/27.
 */
@Service
public class MassMessageServiceImpl extends TenantServiceImplBase<MassMessage, String>
    implements MassMessageService {

    private static final Logger logger = LoggerFactory.getLogger(MassMessageServiceImpl.class);

    @Resource
    private MassMessageDao massMessageDao;


    @Override
    protected MassMessageDao getDAO() {
        return massMessageDao;
    }


    @Override
    public Integer getCount(Long broker_id) {
        return massMessageDao.getCount(broker_id,getTenantId());
    }

    @Override
    public List<MassMessage> getAllByBroker(Long broker_id,Integer page_no,Integer page_size) {
        return massMessageDao.getAllByBroker(broker_id,getTenantId(),page_no,page_size);
    }


    @Override
    @Async
    public void asyncMass(List<String> list,String accessToken,MassMessageForm form,Long broker_id,Integer tenant_id) {
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();// 默认的配置
        try {
            httpclient.start();
            HttpPost request = new HttpPost(SEND_MESSAGE + "?access_token=" + accessToken);
            String muban = "'{'\"touser\":\"{0}\",\"msgtype\":\"news\",\"news\":'{'\"articles\": ['{'\"title\":\"{1}\",\"description\":\"{2}\",\"url\":\"{3}\"'}']'}''}'";
            List<Future<HttpResponse>> respList = new LinkedList<Future<HttpResponse>>();
            for (String str : list) {
                Object[] array = new String[] { str, form.getTitle(), form.getDescription(), form.getUrl() };
                String text = MessageFormat.format(muban, array);
                StringEntity se = new StringEntity(new String(text.getBytes("UTF-8"), "UTF-8"), "utf-8");
                se.setContentType("text/json");
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8"));
                request.setEntity(se);
                respList.add(httpclient.execute(request, null));
            }
            // 获取结果
            MassMessage massMessage = new MassMessage(form.getTitle(), form.getDescription(), form.getUrl());
            massMessage.setTenant_id(tenant_id);
            massMessage.setBroker_id(broker_id);
            for (Future<HttpResponse> future : respList) {
                HttpResponse response = future.get();
                if (response != null) {
                    if (response.getStatusLine().getStatusCode() == 200) {
                        HttpEntity resEntity = response.getEntity();
                        if (resEntity != null) {
                            JSONObject resMap = JSON.parseObject(EntityUtils.toString(
                                    resEntity, "UTF-8"));
                            if ("0".equals(String.valueOf(resMap.get("errcode")))) {
                                massMessage.addSuccessNum();
                            } else {
                                massMessage.addRefuseNum();
                            }
                        }
                    } else {
                        massMessage.addFailNum();
                    }
                }
            }
            this.save(massMessage);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        } catch (ExecutionException e) {
            logger.error(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }
}
